<template>
    <div>
        <el-tabs size="mini" v-model="activeName" type="card" :before-leave='leaveTab' @tab-click="handleClick">
            <el-tab-pane label="基本信息" name="0">
                <el-form
                    class="form-container"
                    :model="form"
                    :rules="rules"
                    ref="postForm"
                    label-width="200px"
                    v-loading="loading">
                    <el-row :gutter="20">
                        <el-col :span="16">
                            <el-form-item label="商品货号：" prop="groupId">
                                <el-input size="mini" v-model="form.groupId" placeholder="请输入商品货号" :disabled="is_view" />
                            </el-form-item>
                            <el-form-item label="商品名称：" prop="title">
                                <el-input size="mini" v-model="form.title" placeholder="请输入商品名称" :disabled="is_view" />
                            </el-form-item>
                            <el-form-item label="商品主图：" prop="listImgUrl">
                                <pic-sel v-if="!is_view" v-model="form.listImgUrl" :maxNum="1"></pic-sel>
                                <pic-view v-else v-model="form.listImgUrl"></pic-view>
                            </el-form-item>
                            <el-form-item label="商品图片：" prop="imgUrls">
                                <pic-sel v-show="!is_view" v-model="form.imgUrls" :maxNum="10"></pic-sel>
                                <pic-view v-show="is_view" v-model="form.imgUrls"></pic-view>
                            </el-form-item>
                            <!-- <el-form-item label="商品视频：" prop="mainVideo">
                            </el-form-item> -->
                            <el-form-item label="分类：" prop="catIds">
                                <el-cascader
                                    v-if="refresh_selector"
                                    style="width:100%;"
                                    filterable
                                    :props="{ value: 'id', label: 'name' }"
                                    size="mini"
                                     :disabled="is_view"
                                    v-model="form.catIds"
                                    :options="cateList"></el-cascader>
                                    <template v-if="historyList && historyList.length > 0">
                                        <p v-for="item in historyList" :key="item.id">
                                            <el-button type="text" @click="selectHistory(item)">
                                                {{ item.parentCateName }} <template v-if="item.cateId>0">/ {{ item.cateName }}</template>
                                            </el-button>
                                        </p>
                                    </template>
                                <!-- <el-select :disabled="is_view" @change="getCateList(false)" size="mini" v-model="form.parentCateId" placeholder="一级分类">
                                    <el-option
                                            v-for="item in parentCateList"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                                <el-select :disabled="is_view" size="mini" class="ml10" v-model="form.cateId" placeholder="二级分类">
                                    <el-option
                                            v-for="item in cateList"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id">
                                    </el-option>
                                </el-select> -->
                            </el-form-item>
                            <el-form-item label="选品库：" prop="industryIdsList">
                                <el-checkbox-group v-model="form.industryIdsList" @change="handleIndustryChange">
                                    <template v-for="item in industryCategoryList">
                                        <el-checkbox :key="item.id" :label="item.id">{{item.name}}</el-checkbox>
                                    </template>
                                </el-checkbox-group>
                            </el-form-item>
                            <el-form-item v-if="!is_view">
                                <el-button type="primary" size="mini" @click="next()">下一步</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="价格库存" name="1">
                <el-form
                    class="form-container"
                    :model="form"
                    :rules="rules2"
                    ref="postForm2"
                    label-width="200px"
                    v-loading="loading">
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="规格类型：" prop="hasSku">
                                <el-radio-group :disabled="form.alibabaGoodsId>0 || is_view" v-model="form.hasSku">
                                    <el-radio :label="0">无</el-radio>
                                    <el-radio :label="1">多规格商品</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="商品规格：" v-show="form.hasSku==1">
                                <div class="attr_box">
                                    <div class="item" v-for="(item, idx) in skuList" :key="item.id">
                                        <div class="line">
                                            <div class="name">规格名：</div>
                                            <div class="line-val">
                                                <el-input size="mini" :disabled="form.alibabaGoodsId>0 || is_view" v-model="item.attrName" placeholder="请填写规格名称" />
                                            </div>
                                            <span class="delete" v-if="!form.alibabaGoodsId && !is_view"><el-button type="text" size="mini" @click="removeSku(idx)">删除规格</el-button></span>
                                        </div>
                                        <div class="line">
                                            <div class="name">规格值：</div>
                                            <div class="line-val" v-for="(item2,idx2) in item.items" :key="item2.id">
                                                <el-input size="mini" :disabled="form.alibabaGoodsId>0 || is_view" v-model="item2.attrValue" :placeholder="getSkuPlaceHolder(idx2)" />
                                            </div>
                                        </div>
                                        <div class="line">
                                            <el-button type="text" size="mini" v-if="!form.alibabaGoodsId && !is_view" @click="addSkuItem(idx)">添加子规格</el-button>
                                        </div>
                                    </div>
                                </div>
                                <el-button v-if="!form.alibabaGoodsId && !is_view" type="primary" size="mini" @click="addSku()">添加规格</el-button>
                                <el-button v-if="!form.alibabaGoodsId && !is_view" type="primary" size="mini" @click="makeSku()">生成规格明细</el-button>
                            </el-form-item>
                            <el-form-item label="规格明细：" v-show="form.hasSku==1">
                                <div style="width:100%;overflow:auto;">
                                    <table id="product-attribute-table" class="ikd-input-table ik-table-layout-fixed">
                                        <thead>
                                        <tr>
                                            <th nowrap></th>
                                            <th nowrap>SKU编号</th>
                                            <th nowrap>规格名</th>
                                            <th nowrap>规格值</th>
                                            <th nowrap>图片</th>
                                            <th nowrap>货号</th>
                                            <th nowrap>供货价(元)<el-button type="text" class="ml10" @click="batchSupplyPrice()">批量</el-button></th>
                                            <th nowrap>批发价(元)<el-button type="text" class="ml10" @click="batchWholesalePrice()">批量</el-button></th>
                                            <th nowrap>建议售价(元)<el-button type="text" class="ml10" @click="batchSalePrice()">批量</el-button></th>
                                            <th nowrap v-show="hasLms">联盟商批发价(元)<el-button type="text" class="ml10" @click="batchWholesalePrice2()">批量</el-button></th>
                                            <th nowrap v-show="hasLms">联盟商建议售价(元)<el-button type="text" class="ml10" @click="batchSalePrice2()">批量</el-button></th>
                                            <th nowrap>库存<el-button type="text" class="ml10" @click="batchInventory()">批量</el-button></th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                            <template v-for="(item, idx) in form.skuInfo">
                                                <tr :key="item.id">
                                                    <td nowrap>
                                                        {{ idx+1 }}
                                                    </td>
                                                    <td>{{ item.id }}</td>
                                                    <td>{{ item.name }}</td>
                                                    <td>{{ item.value }}</td>
                                                    <td><pic-sel v-if="!is_view" v-model="item.imgUrl" :maxNum="1"></pic-sel><pic-view v-model="item.imgUrl" v-else></pic-view></td>
                                                    <td><el-input size="mini" type="text" :disabled="is_view" v-model="item.groupId" /></td>
                                                    <td><el-input size="mini" type="number" :disabled="is_view" @blur="makeMinSupplyPrice" v-model="item.supplyPrice" /></td>
                                                    <td><el-input size="mini" type="number" :disabled="is_view" @blur="makeMinSalewholePrice" v-model="item.wholesalePrice" /></td>
                                                    <td><el-input size="mini" type="number" :disabled="is_view" @blur="makeMinSalePrice" v-model="item.salePrice" /></td>
                                                    <td v-show="hasLms"><el-input size="mini" type="number" :disabled="is_view" @blur="makeMinSalewholePrice2" v-model="item.wholesalePrice2" /></td>
                                                    <td v-show="hasLms"><el-input size="mini" type="number" :disabled="is_view" @blur="makeMinSalePrice2" v-model="item.salePrice2" /></td>
                                                    <td><el-input size="mini" type="number" :disabled="is_view" @blur="makeMinStock" v-model="item.inventory" /></td>
                                                </tr>
                                            </template>
                                        </tbody>
                                    </table>

                                </div>
                            </el-form-item>
                            <el-form-item label="商品供货价格：" prop="minSupplyPrice">
                                <el-input type="number" size="mini" class="w100" v-model="form.minSupplyPrice" placeholder="" :disabled="is_view || form.hasSku==1" />
                            </el-form-item>
                            <el-form-item label="商品批发价格：" prop="minWholesalePrice">
                                <el-input type="number" size="mini" class="w100" v-model="form.minWholesalePrice" placeholder="" :disabled="is_view || form.hasSku==1" />
                            </el-form-item>
                            <el-form-item label="建议在售价格：" prop="minSalePrice">
                                <el-input type="number" size="mini" class="w100"  v-model="form.minSalePrice" placeholder="" :disabled="is_view || form.hasSku==1" />
                            </el-form-item>
                            <el-form-item label="联盟商批发价格：" prop="minWholesalePrice2" v-show="hasLms">
                                <el-input type="number" size="mini" class="w100" v-model="form.minWholesalePrice2" placeholder="" :disabled="is_view || form.hasSku==1" />
                            </el-form-item>
                            <el-form-item label="联盟商建议在售价格：" prop="minSalePrice2" v-show="hasLms">
                                <el-input type="number" size="mini" class="w100"  v-model="form.minSalePrice2" placeholder="" :disabled="is_view || form.hasSku==1" />
                            </el-form-item>
                            <el-form-item label="物流成本：" prop="freightPrice">
                                <el-input type="number" size="mini" class="w100" v-model="form.freightPrice" placeholder="" :disabled="is_view" />
                            </el-form-item>
                            <el-form-item label="商品库存：" prop="inventory">
                                <el-input type="number" size="mini" class="w100"  v-model="form.inventory" placeholder="" :disabled="is_view || form.hasSku==1" />
                            </el-form-item>
                            <!-- <el-form-item label="市场控价：" prop="controlledPriceStatus">
                                <el-radio-group :disabled="is_view" v-model="form.controlledPriceStatus">
                                    <el-radio :label="0">关闭</el-radio>
                                    <el-radio :label="1">开启</el-radio>
                                </el-radio-group>
                            </el-form-item> -->
                            <el-form-item v-if="!is_view">
                                <el-button type="primary" size="mini" @click="prev()">上一步</el-button>
                                <el-button type="primary" size="mini" @click="next()">下一步</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="商品详情" name="2">
                <el-form
                    class="form-container"
                    :model="form"
                    :rules="rules3"
                    ref="postForm3"
                    label-width="200px"
                    v-loading="loading">
                    <el-row :gutter="20">
                        <el-col :span="24">
                                <vue-ueditor-wrap @ready="editorReady" v-model="form.desc" :config="editorConfig" @beforeInit="addCustomButtom" />
                            <el-form-item v-if="!is_view">
                                <el-button type="primary" size="mini" @click="prev()">上一步</el-button>
                                <el-button type="primary" size="mini" @click="next()">保存</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                
            </el-tab-pane>
            
        </el-tabs>
        <pic-list
                :maxNum="0"
                :showPicDialog="showPicDialog"
                @on-selected="picOnSelected"
                @on-close="picOnClose" />

        <el-dialog :title="dialogBatchTitle" :visible.sync="dialogBatchVisible" :close-on-click-modal="false" width="300px">
            <el-form :model="batchForm" ref="batchForm" label-width="80px">
                <template v-if="batchType=='wholesale' || batchType=='sale' || batchType=='wholesale2' || batchType=='sale2'">
                    <el-form-item label="类型：" prop="type">
                        <el-radio-group v-model="batchForm.type">
                            <el-radio :label="0">固定值</el-radio>
                            <el-radio :label="1">上浮比例</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item :label="batchLabel" prop="value">
                        <el-input size="mini" type="number" :placeholder="batchForm.type==1?'上浮的百分比':''" maxlength="10" v-model="batchForm.value" />
                    </el-form-item>
                </template>
                <template v-else>
                    <el-form-item :label="batchLabel" prop="value">
                        <el-input size="mini" type="number" placeholder="" maxlength="10" v-model="batchForm.value" />
                    </el-form-item>
                </template>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="dialogBatchVisible=false">取消</el-button>
                <el-button size="mini" type="primary" @click="okBatch">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import VueUeditorWrap from 'vue-ueditor-wrap'
    import {
        product_save,
        product_detail,
        product_alibaba_detail,
        product_category_history,
        product_category_list
    } from '../../api/product';
    import {
        agency_categories,
        agency_cat_tree
    } from '../../api/agency';
    import {
        _axios
    } from '../../api/index';
    // import {
    //     age_list
    // } from '../../utils/utils';
    // import {
    //     org_school_tree
    // } from '../../api/org/index';
    // import {
    //     isInteger
    // } from '../../utils/validator'
    // import {
    //     next_no
    // } from '../../api/sys';

    export default {
        name: 'agency-create',
        components: {
            VueUeditorWrap,
            'pic-sel': () => import('../../components/PicSel/index'),
            'pic-view': () => import('../../components/PicView/index'),
            'pic-list': () => import('../../components/PicSel/list'),
        },
        props: {
            formData: Object
        },
        computed: {
        },
        watch: {
            formData: {
                immediate: true,
                handler (val) {
                    this.currentId = val.product_id;
                    this.is_alibaba = val.is_alibaba;
                    
                    this.$nextTick(() => {
                        this.$refs.postForm.resetFields();
                        this.$refs.postForm2.resetFields();
                        this.$refs.postForm3.resetFields();
                    });

                    if(this.currentId > 0) {
                        this.is_view = val.is_view;
                        this.getDetail()
                    } else {
                        this.resetTemp();
                    }
                }
            }
        },
        data() {
            return {
                industryCategoryList: [],
                refresh_selector: true,
                historyList: [],
                batchType: "",
                batchLabel: "",
                batchForm: {
                    value: undefined,
                    type: 1,
                },
                dialogBatchTitle: "",
                dialogBatchVisible: false,
                is_alibaba: false,
                editorInstance: undefined,
                editorConfig: {
                    // serverUrl: process.env.VUE_APP_API_BASE + 'backend/file/na/config',
                    UEDITOR_HOME_URL: process.env.BASE_URL + 'UEditor/'
                },
                props: { value: 'id', label:'name', checkStrictly:true },
                categoryForm: {
                    categoryIds: []
                },
                can_edit: true,
                form: {
                    id: 0,
                    title: undefined,
                    parentCateId: undefined,
                    cateId: undefined,
                    hasSku: 0,
                    skuInfo: [],
                    minSalePrice: undefined,
                    minSupplyPrice: undefined,
                    inventory: undefined,
                    controlledPriceStatus: 0,
                    controlledPriceMin: undefined,
                    controlledPriceMax: undefined,
                    imgUrls: "",
                    desc: undefined,
                    skuList: [],
                    auditStatus: 0,
                    alibabaGoodsId: 0,
                    listImgUrl: "",
                    groupId: undefined,
                    minWholesalePrice: undefined,
                    catIds: [],
                    freightPrice: undefined,
                    industryIdsList: [1],

                },
                currentId: 0,
                formStatus: 'create',
                rules: {
                    title: [
                        {
                            required: true,
                            message: '请输商品名称',
                            trigger: 'blur'
                        }
                    ],
                    listImgUrl: [
                        {
                            required: true,
                            message: '请选择商品主图',
                            trigger: 'blur'
                        }
                    ],
                    imgUrls: [
                        {
                            required: true,
                            message: '请选择商品图片',
                            trigger: 'blur'
                        }
                    ],
                    catIds: [
                        {
                            required: true,
                            message: '请选择商品分类',
                            trigger: 'blur'
                        }
                    ],
                    industryIdsList: [
                        {
                            required: true,
                            message: '请选择选品库',
                            trigger: 'blur'
                        }
                    ]
                },
                rules2: {
                    minSupplyPrice: [
                        {
                            required: true,
                            message: '请输入商品供货价格',
                            trigger: 'blur'
                        }
                    ],
                    minSalePrice: [
                        {
                            required: true,
                            message: '请输入建议在售价格',
                            trigger: 'blur'
                        }
                    ],
                    inventory: [
                        {
                            required: true,
                            message: '请输入库存',
                            trigger: 'blur'
                        }
                    ],
                },
                rules3: {
                },
                rules4: {
                },
                loading: false,
                fetchSuccess: true,
                saveLoading: false,
                is_view:false,
                activeName:"0",
                prevActiveName:"0",
                tree_list:[],
                dialogFormVisible: false,
                categoryList:[],
                cateList: [],
                parentCateList:[],
                skuList: [],
                showPicDialog: false,
                desc: undefined,
                hasLms: false,
            }
        },
        created() {
            this.getParentCateList();
            this.getHistoryList();
            this.getCategoryList();
        },
        methods: {
            handleIndustryChange(val) {
                this.getHasLms();
            },
            getHasLms() {
                this.hasLms = false;

                if(this.form.industryIdsList && this.form.industryIdsList.length > 0) {
                    this.form.industryIdsList.forEach((item)=>{
                        if(item == 2) {
                            this.hasLms = true;
                            return false;
                        }
                    })
                }
            },
            getCategoryList() {
                product_category_list().then((res)=>{
                    this.industryCategoryList = res.data;
                }).catch((err)=>{

                })
            },
            selectHistory(item) {
                this.refresh_selector = false;
                // this.form.catIds = undefined;
                this.form.catIds = [];
                this.form.catIds.push("" + item.parentCateId + "");
                if(item.cateId > 0) {
                    this.form.catIds.push("" + item.cateId + "");
                }
                // console.log(this.form.catIds);

                setTimeout(()=>{
                    this.refresh_selector = true;
                }, 0)
            },
            getHistoryList() {
                product_category_history().then((res)=>{
                    this.historyList = res.data;
                }).catch((err)=>{

                })
            },
            editorReady(instance) {
                let self  = this
                this.editorInstance = instance;
                console.log(instance.iframe)
                
            },
            addCustomButtom(editorId) {
                const instance = this;

                window.UE.registerUI('insertimage', function (editor, uiName) {
                    return new window.UE.ui.Button({
                        name: uiName,
                        onclick: function () {
                            instance.showPicDialog = true
                        }
                    });
                })
            },
            picOnSelected(items) {
                if(items && items.length > 0) {
                    items.forEach((item)=>{
                        console.log(item)
                        this.editorInstance.execCommand("inserthtml", "<img src='" + item + "'>")
                //     let field = "<img src='" + this.getItem(items[i]) + "' />";
                //     this.insertHtml(field);
                    })
                }
                // for(let i = 0; i < items.length; i++) {
                //     let field = "<img src='" + this.getItem(items[i]) + "' />";
                //     this.insertHtml(field);
                //
                // }
                //
                // console.log(items)
            },
            picOnClose() {
                this.showPicDialog = false
            },
            makeMinSupplyPrice() {
                // console.log("aaa")
                let p = 0;
                if(this.form.skuInfo && this.form.skuInfo.length > 0) {
                    this.form.skuInfo.forEach((item)=>{
                        if(item.supplyPrice) {
                            if(p == 0 || item.supplyPrice < p) {
                                p = item.supplyPrice;
                            }
                        }
                    })
                }

                this.form.minSupplyPrice = p;
            },
            makeMinSalewholePrice() {
                // console.log("aaa")
                let p = 0;
                if(this.form.skuInfo && this.form.skuInfo.length > 0) {
                    this.form.skuInfo.forEach((item)=>{
                        if(item.wholesalePrice) {
                            if(p == 0 || item.wholesalePrice < p) {
                                p = item.wholesalePrice;
                            }
                        }
                    })
                }

                this.form.minWholesalePrice = p;
            },
            makeMinSalewholePrice2() {
                // console.log("aaa")
                let p = 0;
                if(this.form.skuInfo && this.form.skuInfo.length > 0) {
                    this.form.skuInfo.forEach((item)=>{
                        if(item.wholesalePrice2) {
                            if(p == 0 || item.wholesalePrice2 < p) {
                                p = item.wholesalePrice2;
                            }
                        }
                    })
                }

                this.form.minWholesalePrice2 = p;
            },
            makeMinSalePrice() {
                let p = 0;
                if(this.form.skuInfo && this.form.skuInfo.length > 0) {
                    this.form.skuInfo.forEach((item)=>{
                        if(item.supplyPrice) {
                            if(p == 0 || item.salePrice < p) {
                                p = item.salePrice;
                            }
                        }
                    })
                }
                this.form.minSalePrice = p;
            },
            makeMinSalePrice2() {
                let p = 0;
                if(this.form.skuInfo && this.form.skuInfo.length > 0) {
                    this.form.skuInfo.forEach((item)=>{
                        if(item.salePrice2) {
                            if(p == 0 || item.salePrice2 < p) {
                                p = item.salePrice2;
                            }
                        }
                    })
                }
                this.form.minSalePrice2 = p;
            },
            makeMinStock() {
                let p = 0;
                if(this.form.skuInfo && this.form.skuInfo.length > 0) {
                    this.form.skuInfo.forEach((item)=>{
                        if(item.inventory) {
                            p += Number(item.inventory) || 0
                        }
                    })
                }
                this.form.inventory = p;
            },
            getParentCateList() {
                agency_cat_tree(this.form.agencyId || 0).then((res)=>{
                    this.cateList = res.data
                }).catch((err)=>{
                    this.cateList = res.data
                });
            },
            getCateList(keep) {
                if(!keep) {
                    this.form.cateId = undefined;
                }
                agency_categories(this.form.parentCateId).then((res)=>{
                    this.cateList = res.data;
                }).catch((err)=>{
                    this.cateList = []
                });
            },
            resetTemp() {
                this.form = {
                    id: 0,
                    title: undefined,
                    parentCateId: undefined,
                    cateId: undefined,
                    hasSku: 0,
                    skuInfo: [],
                    minSalePrice: undefined,
                    minSupplyPrice: undefined,
                    inventory: undefined,
                    controlledPriceStatus: 0,
                    controlledPriceMin: undefined,
                    controlledPriceMax: undefined,
                    imgUrls: "",
                    desc: undefined,
                    skuList: [],
                    auditStatus: 0,
                    alibabaGoodsId: 0,
                    listImgUrl: "",
                    groupId: undefined,
                    minWholesalePrice: undefined,
                    catIds: [],
                    freightPrice: undefined,
                    industryIdsList: [1],
                };
                this.skuList = [];
                this.skuList.push(
                    {
                        attrName: undefined,
                        items: [
                            {
                                attrValue: undefined
                            }
                        ]
                    }
                )
                this.can_edit = true;
                this.getHasLms();
            },
            leaveTab(activeName, oldActiveName) {
                if(this.form.id > 0) {
                    return true;
                }
                if(this.prevActiveName == this.activeName) {
                    return false;
                }

                this.prevActiveName = this.activeName
                return true;
            },
            getDetail() {
                if(this.is_alibaba) {
                    product_alibaba_detail(this.currentId).then((res)=>{
                        let data = res.data;

                        this.form.alibabaGoodsId = this.currentId;
                        this.form.id = 0;
                        this.form.title = data.name;
                        this.form.desc = data.description;
                        this.form.imgUrls = data.images;
                        this.form.listImgUrl = data.imgUrl;
                        if(!this.form.imgUrls) {
                            this.form.imgUrls = this.form.listImgUrl;
                        }
                        this.form.groupId = data.productCargoNumber;
                        this.form.inventory = data.amountOnSale;
                        this.form.minSupplyPrice = data.price;
                        this.form.minSalePrice = data.retailPrice;



                        let skuInfo = data.skuInfo;
                        if(skuInfo && skuInfo.length > 0) {
                            this.form.hasSku = 1;
                            let finalSkuList = [];
                            let finalSku = [];
                            skuInfo.forEach((item, idx)=>{
                                if(item.items) {
                                    let skName = [];
                                    let skValue = [];
                                    let skKey = [];
                                    let skAttribute = [];
                                    let skImg = item.items[0].skuImageUrl;

                                    item.items.forEach((item2,idx2)=>{
                                        skName.push(item2.attributeName)
                                        skValue.push(item2.attributeValue)
                                        skAttribute.push(item2.attributeName + ":" + item2.attributeValue)
                                        let hasK = -1, hasVK = -1;
                                        finalSkuList.forEach((sv, sk)=>{
                                            if(sv.attributeId == item2.attributeId) {
                                                hasK = sk;


                                                //循环属性
                                                sv.items.forEach((vv, vk)=>{
                                                // console.log(sv)
                                                    if(vv.attrValue == item2.attributeValue) {
                                                        hasVK = vk;
                                                        return false;
                                                    }
                                                })
                                                return false;
                                            }
                                        });

                                        // console.log(hasK + "-" + hasVK)

                                        if(hasK >= 0) {
                                            //已有
                                            if(hasVK >= 0) {

                                            } else {
                                                finalSkuList[hasK].items.push(
                                                    {
                                                        attrValue: item2.attributeValue
                                                    }
                                                )
                                                hasVK = finalSkuList[hasK].items.length - 1;
                                            }
                                        } else {
                                            finalSkuList.push(
                                                {
                                                    attrName: item2.attributeName,
                                                    attributeId: item2.attributeId,
                                                    items: [
                                                        {
                                                            attrValue: item2.attributeValue
                                                        }
                                                    ]
                                                }
                                            )

                                            hasK = finalSkuList.length - 1;
                                            hasVK = 0;
                                        }

                                        skKey.push(hasK + ":" + hasVK)
                                    })

                                    finalSku.push(
                                        {
                                            key: skKey.join(","),
                                            name: skName.join(","),
                                            value: skValue.join(","),
                                            imgUrl: skImg,
                                            inventory: item.amountOnSale,
                                            salePrice: item.cpsSuggestPrice,
                                            supplyPrice: item.consignPrice,
                                            wholesalePrice: item.consignPrice,
                                            alibabaSkuId: item.id,
                                            attribute: skAttribute.join(", ")
                                        }
                                    )
                                }
                            });
                            this.skuList = finalSkuList;
                            this.form.skuInfo = finalSku;
                            this.makeMinSupplyPrice();
                            this.makeMinSalePrice();
                            this.makeMinStock();
                                            // console.log(finalSku)
                        } else {
                            this.form.hasSku = 0;
                        }
                    }).catch((err)=>{

                    })
                } else {
                    product_detail(this.currentId).then(response => {
                        let form = response.data;
                        this.desc = form.desc;
                        this.form.desc = undefined;
                        // this.getDescription();

                        _axios.get(this.desc).then((res2)=>{
                            this.form.desc = res2.data;
                            // console.log(res2.data)
                        }).catch((err)=>{

                        })

                        this.form = form;
                        this.form.catIds = [];
                        if(this.form.parentCateId > 0) {
                            this.form.catIds.push("" + this.form.parentCateId + "");

                            if(this.form.cateId > 0) {
                                this.form.catIds.push("" + this.form.cateId + "");
                            }
                        //     this.getCateList(true);
                        }
                        // if(!this.form.skuInfo) {
                        //     this.form.skuInfo = [];
                        // }

                        // console.log(this.form)
                        this.skuList = this.form.skuList;

                        if(!this.skuList || this.skuList.length < 1) {
                            this.skuList = [];
                            this.skuList.push(
                                {
                                    attrName: undefined,
                                    items: [
                                        {
                                            attrValue: undefined
                                        }
                                    ]
                                }
                            )
                        }
                        this.getHasLms();
                        this.formStatus = "update";
                        this.can_edit = true
                    }).catch(()=>{
                        this.formStatus = ""
                    });

                }
            },
            cancel() {
                this.$emit('cancelCreate');
            },
            finalSave() {
                this.form.skuList = [];
                if(this.skuList && this.skuList.length > 0) {
                    this.skuList.forEach((item, idx)=>{
                        let finalItem = [];
                        if(item && item.attrName && item.items && item.items.length > 0) {
                            item.items.forEach((item2, idx2)=>{
                                if(item2.attrValue) {
                                    item2.key = idx2;

                                    finalItem.push(item2);
                                }
                            })
                        }

                        if(finalItem.length > 0) {
                            this.form.skuList.push(
                                {
                                    id: item.id,
                                    items: finalItem,
                                    key: idx,
                                    attrName: item.attrName
                                }
                            )
                        }
                    })
                }
                this.form.parentCateId = (this.form.catIds && this.form.catIds.length > 0) ? this.form.catIds[0] : 0;
                this.form.cateId = (this.form.catIds && this.form.catIds.length > 1) ? this.form.catIds[1] : 0;
                this.saveLoading = true;
                product_save(this.form)
                    .then(() => {
                        this.saveLoading = false;
                        this.$message.success(this.form.id > 0 ? "商品信息已保存" : "成功添加商品");
                        this.$emit('okCreate');
                    }).catch((err)=>{
                    this.saveLoading = false;
                })

            },
            next() {
                let form = "";
                if(this.activeName == "0") {
                    form = "postForm";
                } else if(this.activeName == "1") {
                    form = "postForm2";
                } else if(this.activeName == "2") {
                    form = "postForm3";
                }

                if(form) {
                    this.$refs[form].validate(valid => {
                        if(valid) {
                            if(this.activeName == "2") {
                                //最后一步
                                let hasInvalid = false;
                                if(this.form.hasSku == "1") {
                                    this.form.skuInfo.forEach((item)=>{
                                        let cb = parseFloat(item.supplyPrice) || 0;

                                        let sj = parseFloat(item.wholesalePrice) || 0;

                                        if(sj < cb) {
                                            hasInvalid = true;
                                            this.$confirm('您设置的批发价低于供货价，是否确认?', '提示', {
                                                confirmButtonText: '确认',
                                                cancelButtonText: '去修改',
                                                type: 'warning'
                                            })
                                                .then(() => {
                                                    this.finalSave();
                                                }).catch(()=>{});
                                            return false;
                                        }
                                    });
                                } else {
                                    if(this.form.minWholesalePrice < this.form.minSupplyPrice) {
                                        hasInvalid = true;
                                        this.$confirm('您设置的批发价低于供货价，是否确认?', '提示', {
                                            confirmButtonText: '确认',
                                            cancelButtonText: '去修改',
                                            type: 'warning'
                                        })
                                            .then(() => {
                                                this.finalSave();
                                            }).catch(()=>{});
                                        return false;
                                    }
                                }

                                if(!hasInvalid) {
                                    this.finalSave();
                                }
                            } else {
                                this.prevActiveName = this.activeName
                                this.activeName = "" + (parseInt(this.activeName) + 1) + "";   
                            }
                        }
                    });
                }
            },
            prev() {
                this.prevActiveName = this.activeName
                this.activeName = "" + (parseInt(this.activeName) - 1) + "";
            },
            handleClick(tab, event) {
                // this.prevActiveName = this.activeName
                // console.log(this.prevActiveName + "-" + this.activeName)
            },
            removeSku(idx) {
                this.$confirm('删除会重置规格明细, 是否操作?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(()=>{
                    let l = [];
                    this.skuList.forEach((item, i)=>{
                        if(item && i != idx) {
                            l.push(item);
                        }
                    })

                    if(l.length > 0) {
                        this.skuList = l;
                        // console.log(this.skuList)
                        this.finalMakeSku();

                    }
                })
            },
            delete_item(idx) {
                this.$confirm('确定删除这个类目吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        let items = [];

                        this.categoryList.forEach((item, item_idx)=>{
                            if(item_idx != idx) {
                                items.push(item);
                            }
                        })

                        this.categoryList = items;
                    }).catch(()=>{});
            },
            addSku() {
                this.skuList.push(
                    {
                        attrName: undefined,
                        items: [
                            {
                                attrValue: undefined
                            }
                        ]
                    }
                )
            },
            getSkuPlaceHolder(idx) {
                return "请填写规格值" + (idx + 1)
            },
            addSkuItem(idx) {
                this.skuList[idx].items.push(
                    {
                        attrValue: undefined
                    }
                )
                this.skuList[idx].items.push(
                    {
                        attrValue: undefined
                    }
                )
                this.skuList[idx].items.push(
                    {
                        attrValue: undefined
                    }
                )
                this.skuList[idx].items.push(
                    {
                        attrValue: undefined
                    }
                )
            },
            concatSkuArr(arr1, arr2) {
                let r = [];
                arr1.forEach((item)=>{
                    arr2.forEach((item2)=>{
                        let n = item + "," + item2;
                        r.push({
                            key: item.key + "," + item2.key,
                            name: item.name + "," + item2.name,
                            value: item.value + "," + item2.value,
                            attribute: item.attribute + ", " + item2.attribute
                        })
                    })
                })


                return r;
            },
            finalMakeSku() {
                    var list = [];
                    for(var i = 0; i < this.skuList.length; i++) {
                        if(this.skuList[i] && this.skuList[i].items && this.skuList[i].items.length > 0) {
                            if(!this.skuList[i].attrName) {
                                continue;
                            }
                            let t = [];
                            for(var j = 0; j < this.skuList[i].items.length; j++) {
                                if(!this.skuList[i].items[j].attrValue) {
                                    continue;
                                }
                                let k = i + ":" + j;
                                t.push(
                                    {
                                        key: k,
                                        name: this.skuList[i].attrName,
                                        value: this.skuList[i].items[j].attrValue,
                                        attribute: this.skuList[i].attrName + ":" + this.skuList[i].items[j].attrValue
                                    }
                                )
                            }
                            if(list.length > 0) {
                                list = this.concatSkuArr(list, t);
                            } else {
                                list = t.slice();
                            }
                        }
                    }
                    // console.log(list)

                    list.forEach((item)=>{
                        item.imgUrl = undefined;
                        item.inventory = undefined;
                        item.salePrice = undefined;
                        item.supplyPrice = undefined;
                        item.wholesalePrice = undefined;
                        item.groupId = undefined;
                    });

                    this.form.skuInfo = list;
            },
            makeSku() {

                this.$confirm('生成规格明细会重置列表, 是否操作?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then((res)=>{
                    this.finalMakeSku();

                })
            },
            batchSupplyPrice() {
                this.dialogBatchTitle = "批量设置供货价";
                this.batchForm.value = undefined;
                this.batchLabel = "供货价";
                this.batchType = "supply";
                this.dialogBatchVisible = true;
            },
            batchSalePrice() {
                this.dialogBatchTitle = "批量设置建议售价";
                this.batchForm.value = undefined;
                this.batchLabel = "建议售价";
                this.batchType = "sale";
                this.dialogBatchVisible = true;
            },
            batchSalePrice2() {
                this.dialogBatchTitle = "批量设置联盟商建议售价";
                this.batchForm.value = undefined;
                this.batchLabel = "建议售价";
                this.batchType = "sale2";
                this.dialogBatchVisible = true;
            },
            batchWholesalePrice() {
                this.dialogBatchTitle = "批量设置批发价";
                this.batchForm.value = undefined;
                this.batchLabel = "批发价";
                this.batchType = "wholesale";
                this.dialogBatchVisible = true;
            },
            batchWholesalePrice2() {
                this.dialogBatchTitle = "批量设置联盟商批发价";
                this.batchForm.value = undefined;
                this.batchLabel = "联盟商批发价";
                this.batchType = "wholesale2";
                this.dialogBatchVisible = true;
            },
            batchInventory() {
                this.dialogBatchTitle = "批量设置库存";
                this.batchForm.value = undefined;
                this.batchLabel = "库存";
                this.batchType = "inventory";
                this.dialogBatchVisible = true;
            },
            okBatch() {
                if(typeof this.batchForm.value == "undefined") {
                    this.$message.error("批量数值必填");
                } else {
                    let v = $.trim(this.batchForm.value);

                    if(v.length < 1) {
                        this.$message.error("批量数值必填");
                    } else {
                        v = Number(v) || 0;

                        if(this.form.skuInfo && this.form.skuInfo.length > 0) {
                            this.form.skuInfo.forEach((item)=>{
                                if(this.batchType == "supply") {
                                    item.supplyPrice = v;
                                } else if(this.batchType == "sale") {
                                    if(this.batchForm.type == 1) {
                                        //上浮比例
                                        let vv = parseFloat(item.salePrice) || 0;
                                        item.salePrice = (vv * (1 + v / 100)).toFixed(2)
                                    } else {
                                        item.salePrice = v;
                                    }
                                } else if(this.batchType == "wholesale") {
                                    if(this.batchForm.type == 1) {
                                        //上浮比例
                                        let vv = parseFloat(item.supplyPrice) || 0;
                                        item.wholesalePrice = (vv * (1 + v / 100)).toFixed(2)
                                    } else {
                                        item.wholesalePrice = v;
                                    }
                                } else if(this.batchType == "inventory") {
                                    item.inventory = v;
                                } else if(this.batchType == "sale2") {
                                    if(this.batchForm.type == 1) {
                                        //上浮比例
                                        let vv = parseFloat(item.salePrice2) || 0;
                                        item.salePrice2 = (vv * (1 + v / 100)).toFixed(2)
                                    } else {
                                        item.salePrice2 = v;
                                    }
                                } else if(this.batchType == "wholesale2") {
                                    if(this.batchForm.type == 1) {
                                        //上浮比例
                                        let vv = parseFloat(item.wholesalePrice2) || 0;
                                        item.wholesalePrice2 = (vv * (1 + v / 100)).toFixed(2)
                                    } else {
                                        item.wholesalePrice2 = v;
                                    }
                                }
                            })
                        }

                        if(this.batchType == "supply") {
                            this.makeMinSupplyPrice();
                        } else if(this.batchType == "sale") {
                            this.makeMinSalePrice();
                        } else if(this.batchType == "wholesale") {
                            this.makeMinSalewholePrice();
                        } else if(this.batchType == "inventory") {
                            this.makeMinStock();
                        } else if(this.batchType == "sale2") {
                            this.makeMinSalePrice2();
                        } else if(this.batchType == "wholesale2") {
                            this.makeMinSalewholePrice2();
                        }
                        this.dialogBatchVisible = false;
                    }
                }
            }
        }
    }
</script>
<style lang="scss" scoped>
.attr_box {
    background: #f3f3f3;
    padding-top: 17px;
    border-radius: 4px;

    .item {
        position: relative;
        .line {
            padding-left: 70px;
            padding-right: 30px;
            display: -webkit-box;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-align: center;
            -ms-flex-align: center;
            align-items: center;
            position: relative;
            font-size: 14px;
            -ms-flex-wrap: wrap;
            flex-wrap: wrap;

            .name {
                    position: absolute;
                    top: 0;
                    left: 20px;
                    line-height: 34px;
                    text-align: center;
                    color: #333;
            }
            .line-val {
                    width: 240px;
                    margin: 0 20px 4px 0;
            }

            .delete {
                right: 20px;
                top: 0;
                position: absolute;
            }
            .add {
                left: 70px;
                bottom: 0;
                position: absolute;

            }
        }
        
    }
}
</style>